package bpd;

import static org.junit.Assert.assertTrue;
import net.sf.robocode.io.Logger;
import bpd.test.RobotTestBed;
import robocode.control.events.RoundEndedEvent;
import robocode.control.events.TurnEndedEvent;
import robocode.control.snapshot.IRobotSnapshot;

/**
 * Illustrates JUnit testing of the Robocode robot PanzerBot. This test simply verifies that this
 * robot will evade a bullet at least once during each round.
 * 
 * @author BJ Peter DeLaCruz
 * @version 1.0
 */
public class TestPanzerBotAvoidBullet extends RobotTestBed {
  /** True if the robot avoided a bullet at least once during each round. */
  boolean avoidedBullet = false;
  /** Current energy level of the robot. */
  double currentEnergy = 0.0;
  /** Previous energy level of the robot. */
  double previousEnergy = 0.0;
  /** Information about the robot during a turn. */
  String info = "";

  /**
   * Specifies that Fire and PanzerBot are to be matched up in this test case.
   * 
   * @return A comma-delimited list of robots in this match
   */
  @Override
  public String getRobotNames() {
    return "sample.Fire,bpd.PanzerBot";
  }
  
  /**
   * This test runs for twenty rounds.
   * 
   * @return The number of rounds in this test 
   */
  @Override
  public int getNumRounds() {
    return 20;
  }

  /**
   * After each turn, check to see if PanzerBot turned to avoid an enemy's bullet.  If so, set the
   * corresponding flag.
   * 
   * @param event Information about the current state of the battle
   */
  @Override 
  public void onTurnEnded(TurnEndedEvent event) {
    
    int turn = event.getTurnSnapshot().getTurn(); // Get turn number
    IRobotSnapshot robot = event.getTurnSnapshot().getRobots()[1];
    
    if (turn % 2 == 0) {
      currentEnergy = robot.getEnergy();
    }
    else {
      previousEnergy = currentEnergy;
    }
    
    // PanzerBot only moves when it detects a change in an enemy's energy level. Thus, if
    // PanzerBot's velocity does not equal to zero, then it must have moved because an enemy fired
    // at it.
    if (robot.getVelocity() != 0.0 && (currentEnergy - previousEnergy == 0.0)) {
      avoidedBullet = true;
      info = "Robot turned to avoid bullet at least once during this round.\n\n";
    }

  }
  
  /**
   * Asserts that PanzerBot turned to avoid an enemy's bullet.
   * 
   * @param event Details about the completed round
   */
  @Override
  public void onRoundEnded(RoundEndedEvent event) {
    
    assertTrue("Check Avoided Bullet", avoidedBullet);
    Logger.realOut.print(info);
    
  }
  
  /**
   * Returns false, thus making the robots always start at a random position each time.
   * 
   * @return False if the battle will not be deterministic, true otherwise
   */
  @Override
  public boolean isDeterministic() {
    return false;
  }
  
}
